package com.ctrip.ec.biz.dao.invite;
import com.ctrip.ec.biz.entity.member.MemberEntity;
import com.ctrip.ec.dal.DaoBase;
import com.ctrip.ec.biz.entity.invite.InviteCodeEntity;
import com.ctrip.ec.dal.DbAccess;
import com.ctrip.ec.dal.EntityBase;
import org.springframework.stereotype.Service;

import java.sql.SQLException;
import java.util.List;

@Service
public class InviteCodeDao extends DaoBase<InviteCodeEntity> {
    public InviteCodeDao() {
        super(InviteCodeEntity.class);
    }
    public InviteCodeDao(DbAccess db) {
        super(InviteCodeEntity.class,db);
    }

    public InviteCodeEntity top(Long memberId) throws SQLException {
        String sql = "select * from " + this.getTableName() + " where in_use=0 and member_id=? limit 1";
        List<InviteCodeEntity> list = this.db.query(InviteCodeEntity.class,sql,memberId);
        if(list.size()>0){
            return list.get(0);
        }else{
            return null;
        }
    }

    public Long used(Long memberId) throws SQLException {
        String sql = "select count(*) from " + this.getTableName() + " where in_use=1  and member_id=?";
        Long count = this.db.getScalar(Long.class, sql, memberId);
        return count;

    }

    public Long total(Long memberId) throws SQLException {
        String sql = "select count(*) from " + this.getTableName() + " where member_id=?";
        Long count = this.db.getScalar(Long.class,sql,memberId);
        return count;
    }

    public List<InviteCodeEntity> listTopUnUse(int count) throws SQLException {
        String sql = "select * from " + this.getTableName() + " where in_use=0 and member_id in (select id from " + EntityBase.getTableName(MemberEntity.class)+ " ) limit " + count;
        List<InviteCodeEntity> list = this.db.query(InviteCodeEntity.class,sql);
        return list;
    }

    /**
     * 清理用户不存的邀请码
     */
    public void clear() {


    }
}
